package kr.hkit.barontest;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.androidtest.R;
import com.google.gson.JsonParser;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class HeroText extends Activity {
	ListView list;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.parser);
		list = (ListView) findViewById(R.id.orderListView);
		new ParsingXml().execute("Hero.json");
	}

	private class ParsingXml extends AsyncTask<String, Void, ArrayList<Item>> {
		ProgressDialog progressDlg;

		protected ArrayList<Item> doInBackground(String... params) {
			StringBuilder sb = new StringBuilder();
			String str = null;
			BufferedReader br = null;
			try {
				br = new BufferedReader(new InputStreamReader(
						openFileInput(params[0])));
				while ((str = br.readLine()) != null) {
					sb.append(str);
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					br.close();
				} catch (IOException e) {
				}
			}
			return parsingXml(sb.toString());
		}

		private ArrayList<Item> parsingXml(String xml) {
			ArrayList<Item> arLists = new ArrayList<>();
			Item item = null;
			try {
				JSONArray ja = new JSONArray(xml);
				for (int i = 0; i < ja.length(); i++) {
					JSONObject jsonObj = ja.getJSONObject(i);
					item = new Item();
					item.setItemName(jsonObj.getString("Product"));
					item.setItemMaker(jsonObj.getString("Maker"));

					arLists.add(item);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return arLists;
		}

		protected void onPreExecute() {
			progressDlg = ProgressDialog.show(HeroText.this, "Wait",
					"Xml Parsing...");
		}

		protected void onPostExecute(ArrayList<Item> result) {
			progressDlg.dismiss();
			MyAdapter adapter = new MyAdapter(HeroText.this, result);
			list.setAdapter(adapter);
		}
	}// end of class ParsingXml

}// end of class JsonParser
